<template>
  <div class="checkTask">
    <!-- 导航栏 -->
    <div class="header_body">
      <header-nav :leftArrow="true" titelText="任务检查"></header-nav>
    </div>

    <div class="checkForm">
      <upload-pictrue :fileType="3"  :titelText="'营业执照/身份证'" :fileList="licenseFileList" :imgType="0" :maxCount="100"
        @fileListFun="licenseFileListFun"></upload-pictrue>
      <div class="line10"></div>
      <upload-pictrue :fileType="3" :titelText="'建筑物照片'" :fileList="fileList" :imgType="0" :maxCount="100"
        @fileListFun="fileListFun"></upload-pictrue>
      <div class="line10"></div>
      <div class="yinH">
        <div class="yinH-title">隐患信息</div>
        <div class="yinH-content" v-for="(item, index) in checkForm.taskCheckFillList" :key="index">
          <div class="top">
            <div class="topT"><span v-if="checkForm.checkResult == 2" style="color: #ee0a24; margin-right: 2px">*</span>第{{ index + 1 }}条</div>
            <div class="topD" @click="delYH(index)" v-if="checkForm.taskCheckFillList.length > 1">
              删除
            </div>
          </div>
          <van-field v-model="item.dangerDesc" rows="2" autosize maxlength="256" type="textarea" placeholder="请输入" />
          <div>
            <upload-pictrue :fileType="3" :isRequir="checkForm.checkResult == 2" :titelText="'隐患照片（可传三张）'" :fileList="item.photoUrls"
              :imgType="0"></upload-pictrue>
          </div>
        </div>
        <div class="addBtn" @click="addYH">添加隐患</div>
      </div>
      <div class="line10"></div>

      <div class="yinH">
        <div class="yinH-title noBorder">备注</div>
        <div class="yinH-content">
          <van-field v-model="checkForm.remark" rows="2" autosize type="textarea" placeholder="请输入备注" maxlength="256" />

        </div>

      </div>
      <div class="result1">
        <div class="title">
          <span style="color: #ee0a24; margin-right: 2px">*</span>结果判断
        </div>
        <van-radio-group v-model="checkForm.checkResult" direction="horizontal">
          <van-radio :name="1" style="margin-right: 52px">合格</van-radio>
          <van-radio :name="2">不合格</van-radio>
        </van-radio-group>
      </div>
      <van-field v-if="signFlag == ''" style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link
        required readonly label="主办人签字" :placeholder="signNames[0] == '' ? '去签字' : '查看签名'" @click="goSign(0)" />
      <div class="result1" :style="sign1 == '' ? 'justify-content: space-between' : ''" v-else>
        <div class="title">
          <span style="color: #ee0a24; margin-right: 2px">*</span>主办人签字
        </div>
        <div style="
            color: #a6a6a6;
            flex-grow: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
          " @click="oneSign()" v-if="sign1 == ''">
          <div style="color: var(--van-primary-color);
            padding: 5px 12px;
            border: 1px solid rgba(23, 100, 206, 1);
            border-radius: 4px;">
            一键签名
          </div>
          <img style="width: 11px; height: 18px" src="../../assets/images/icon_chevron.png" alt="" />
        </div>
        <div style="
            color: #a6a6a6;
            flex-grow: 1;
            display: flex;
            justify-content: space-between;
          " v-else @click="goSign(0)">
          <div>查看签名</div>
          <img style="width: 11px; height: 18px" src="../../assets/images/icon_chevron.png" alt="" />
        </div>
      </div>
      <van-field style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link required readonly
        label="协办人签字" :placeholder="signNames[1] == '' ? '去签字' : '查看签名'" @click="goSign(1)" />
      <van-field style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link required readonly
        label="被检查单位人员签字" :placeholder="signNames[2] == '' ? '去签字' : '查看签名'" @click="goSign(2)" />
      <div class="submitBtn">
        <van-button plain block class="btn-left" type="primary" native-type="submit" style="margin-right: 8px"
          @click="submitCheck('0')">
          保存当前并返回
        </van-button>
        <van-button block class="btn-right" type="primary" @click="submitCheck('1')">
          提交检查
        </van-button>
      </div>
    </div>
    <!-- 签名 -->
    <van-popup v-model:show="signPicker" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature background-color="#F7F7F7" v-if="sign1 == ''" @submit="signSubmit" @clear="onClear" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image style="width: 100%;height: 500px;" :src="sign1" />
        <div style="width:100%;display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(1)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(1)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup v-model:show="signPicker2" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature height="600px" background-color="#F7F7F7" v-if="sign2 == ''" @submit="signSubmit2"
        @clear="onClear2" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image style="width: 100%;height: 500px;" :src="sign2" />
        <div style="width:100%;display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(2)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(2)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup v-model:show="signPicker3" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature background-color="#F7F7F7" v-if="sign3 == ''" @submit="signSubmit3" @clear="onClear3" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image style="width: 100%;height: 500px;" :src="sign3" />
        <div style="width:100%; display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(3)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(3)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { showNotify, showSuccessToast, showFailToast, showConfirmDialog } from 'vant'
import { imgUrlToBase64 } from '../../util/util'
const { useVision, usePublic } = $globalStore
const router = useRouter()
const route = useRoute()
const id = ref(route.query.id)
const signFlag = ref(JSON.parse(sessionStorage.getItem('userInfo')).userSign)
//检查图片信息
const fileList = ref([])
const fileListFun = (val) => {
  checkForm.value.placePhotoUrl = val.join(',')
}
//营业执照/身份证信息
const licenseFileList = ref([])
const licenseFileListFun = (val) => {
  checkForm.value.buseLicence = val.join(',')
}

const checkForm = ref({
  taskCheckFillList: [
    {
      id: '',
      dangerDesc: '',
      photoUrls: [],
    },
  ], //隐患信息
  placePhotoUrl: '', // 检查照片
  checkResult: 1, //判断结果 1合格 2不合格
  checkerSign: '', //检查人签字
  enterpriserSign: '', //被检查单位人员签名
  type: '',
  id: '',
  remark: '', //备注
})

//添加隐患
const addYH = () => {
  checkForm.value.taskCheckFillList.push({
    id: '',
    dangerDesc: '',
    photoUrls: [],
  })
}

//删除隐患
const delYH = (index) => {
  checkForm.value.taskCheckFillList.splice(index, 1)
}

//去签字
const signPicker = ref(false)
const signPicker2 = ref(false)
const signPicker3 = ref(false)
const signNames = ref(['', '', ''])
const sign1 = ref('')
const sign2 = ref('')
const sign3 = ref('')
const goSign = (val) => {
  if (val == 0) {
    signPicker.value = true
  } else if (val == 1) {
    signPicker2.value = true
  } else {
    signPicker3.value = true
  }
}

const oneSign = async () => {
  const d = await usePublic.bindFileUrl(
    JSON.parse(sessionStorage.getItem('userInfo')).userSign
  )
  if (d.code == 0) {
    signNames.value[0] = d.data
    imgUrlToBase64(d.data).then((r) => {
      sign1.value = r
    })
  }
}

const signSubmit = async (val) => {
  sign1.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[0] = res.data.fileIds[0]
    }
  } else {
    signNames.value[0] = ''
  }
  signPicker.value = false
}

const signSubmit2 = async (val) => {
  sign2.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[1] = res.data.fileIds[0]
    }
  } else {
    signNames.value[1] = ''
  }
  signPicker2.value = false
}
const signSubmit3 = async (val) => {
  sign3.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[2] = res.data.fileIds[0]
    }
  } else {
    signNames.value[2] = ''
  }
  signPicker3.value = false
}

const reSign = (val) => {
  if (val == 1) {
    sign1.value = ''
  } else if (val == 2) {
    sign2.value = ''
  } else {
    sign3.value = ''
  }
}

const close = (val) => {
  if (val == 1) {
    signPicker.value = false
  } else if (val == 2) {
    signPicker2.value = false
  } else {
    signPicker3.value = false
  }
}

const isDesc = (arr) => {
  let newArr = arr.filter(item => item.dangerDesc == '')
  console.log(newArr.length > 0);
  return newArr.length > 0
}
const isPhoto = (arr) => {
  let newArr = arr.filter(item => item.photoUrls.length == 0)
  console.log(newArr.length, 'newArr');
  return newArr.length > 0
}
//提交检查
const submitCheck = async (val) => {
  if (val == '1') {
    if (checkForm.value.placePhotoUrl == '') {
      return showNotify({ type: 'danger', message: '请上传建筑物照片' })
    } else if (checkForm.value.checkResult == '') {
      return showNotify({ type: 'danger', message: '请选择判断结果' })
    } else if (isDesc(checkForm.value.taskCheckFillList) && checkForm.value.checkResult == 2) {
      return showNotify({ type: 'danger', message: '请填写隐患信息' })
    } else if (isPhoto(checkForm.value.taskCheckFillList)&& checkForm.value.checkResult == 2) {
      return showNotify({ type: 'danger', message: '请上传隐患照片' })
    } else if (signNames.value[0] == '' || signNames.value[1] == '') {
      return showNotify({ type: 'danger', message: '请检查人签名' })
    } else if (signNames.value[2] == '') {
      return showNotify({ type: 'danger', message: '请被检查单位人员签名' })
    }
  }
  checkForm.value.type = val
  checkForm.value.id = id.value
  checkForm.value.checkerSign = signNames.value[0] + ',' + signNames.value[1]
  checkForm.value.enterpriserSign = signNames.value[2]
  if (checkForm.value.checkResult == 1 && val == 1) {
    showConfirmDialog({
      title: '提示',
      message: '当前检查已合格，是否结束任务？',
    })
      .then(() => {
        uploadTask(checkForm.value, val)
      })
      .catch(() => {
        // on cancel
      })
  } else {
    if (checkForm.value.checkTypeName == '其他') {
      showConfirmDialog({
        title: '提示',
        message: '是否结束任务？',
      })
        .then(() => {
          uploadTask(checkForm.value, val)
        })
        .catch(() => {
          // on cancel
        })
    } else {
      uploadTask(checkForm.value, val)
    }
  }
}

const uploadTask = async (params, val) => {
  const res = await useVision.uploadTask(checkForm.value)
  if (res.code == 0) {
    if (val == '0') {
      showSuccessToast('保存成功')
    } else {
      showSuccessToast('提交成功')
    }
    router.push({ name: 'superviseList' })
  } else {
    showFailToast(res.message)
  }
}

onMounted(async () => {
  if (id.value) {
    fileList.value = []
    licenseFileList.value = []
    const res = await useVision.taskInfo(id.value)
    if (res.code == 0) {
      checkForm.value.remark = res.data.remark

      checkForm.value.placePhotoUrl = res.data.placePhotoUrl
      if (res.data.placePhotoUrl != '') {
        let arr = res.data.placePhotoUrl.split(',')
        arr.forEach(async (element) => {
          const r = await usePublic.bindFileUrl(element)
          if (r.code == 0) {
            fileList.value.push(r.data)
          }
        })
      }
      checkForm.value.buseLicence = res.data.buseLicence
      if (res.data.buseLicence != '') {
        let arr = res.data.buseLicence.split(',')
        arr.forEach(async (element) => {
          const r = await usePublic.bindFileUrl(element)
          if (r.code == 0) {
            licenseFileList.value.push(r.data)
          }
        })
      }
      checkForm.value.checkTypeName = res.data.checkTypeName
      checkForm.value.taskCheckFillList = []
      if (res.data.taskCheckFillList.length > 0) {
        res.data.taskCheckFillList.forEach(async (item) => {
          let urlarr = []
          let newList = item.photoUrls.map(async item => {
            let arr = await usePublic.bindFileUrl(item)
            urlarr.push(arr.data)
            return arr
          })
          await Promise.all(newList);
          let obj = {
            id: item.id,
            dangerDesc: item.dangerDesc,
            photoUrls: urlarr
          }
          checkForm.value.taskCheckFillList.push(obj)
        })
      } else {
        checkForm.value.taskCheckFillList = [
          {
            id: '',
            dangerDesc: '',
            photoUrls: [],
          },
        ]
      }
      checkForm.value.checkResult = res.data.checkResult
      if (res.data.checkerSign != '') {
        let s = res.data.checkerSign.split(',')
        const r = await usePublic.bindFileUrl(s[0])
        if (r.code == 0) {
          signNames.value[0] = r.data
          imgUrlToBase64(r.data).then((s) => {
            sign1.value = s
          })
        }
        if (s[1]) {
          const d = await usePublic.bindFileUrl(s[1])
          if (d.code == 0) {
            signNames.value[1] = d.data
            imgUrlToBase64(d.data).then((r) => {
              sign2.value = r
            })
          }
        }
      }
      if (res.data.enterpriserSign != '') {
        const t = await usePublic.bindFileUrl(res.data.enterpriserSign)
        if (t.code == 0) {
          signNames.value[2] = t.data
          imgUrlToBase64(t.data).then((r) => {
            sign3.value = r
          })
        }
      }

    }
  }
})
</script>

<style lang="scss" scoped>
.checkTask {
  width: 100%;
  height: calc(100%);
  overflow-y: hidden;
  background-color: #ffffff;

  .checkForm {
    width: 100%;
    height: calc(100% - 122px);
    overflow-y: auto;
    margin-top: 46px;

    .yinH {


      .yinH-title {
        padding: 16px;
        font-size: 16px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 24px;
        color: #2b2b2b;
        border-bottom: 1px solid #f5f5f5;
      }

      .yinH-content {
        border-bottom: 1px solid #f5f5f5;

        .top {
          display: flex;
          justify-content: space-between;
          font-size: 16px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 24px;
          padding: 16px 16px 0px 16px;

          .topT {
            color: #4d4d4d;
          }

          .topD {
            color: #ff4d4d;
          }
        }
      }

      .noBorder {
        border: none
      }

      .addBtn {
        height: 47px;
        line-height: 47px;
        font-size: 16px;
        font-weight: 400;
        letter-spacing: 0px;
        color: var(--van-primary-color);
        text-align: center;
      }
    }

    .result1 {
      padding: 16px;
      display: flex;
      border-bottom: 1px solid #f5f5f5;
      align-items: center;

      .title {
        width: 122px;
        font-size: 16px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 24px;
        color: #4d4d4d;
      }
    }
  }
}

.line10 {
  width: 100%;
  height: 10px;
  background-color: #f7f7f7;
}

.checkForm .van-cell:after {
  left: 16px !important;
  right: 16px !important;
}
</style>
